<!--
 * @Author: HeAo
 * @Date: 2021-10-14 11:47:06
 * @LastEditTime: 2021-10-14 11:56:12
 * @LastEditors: HeAo
 * @Description: 
 * @FilePath: \web2103-2105\web2105\3-2-Vue\day06\4-vuex应用.html
 * 别乱动！
-->
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script src="../js/vue.js"></script>
  <script src="../js/vuex.js"></script>
  <script src="../js/axios.js"></script>
</head>

<body>
  <div id="app">
    <ul>
      {{categories}}
      <li v-for="(item, index) in categories" :key="index">
        栏目编号：{{item.id}}
        栏目名称：{{item.name}}
      </li>
    </ul>
  </div>
  <script>
    // 1.声明状态机Vuex实例
    let store = new Vuex.Store({
      state: {
        // 用来存放状态机中的数据
        msg: 'hello vuex',
        categories: []
      },
      getters: {
        upperMsg(state) {
          return state.msg.toUpperCase()
        }
      },
      mutations: {
        // 突变，修改state中数据的唯一方法
        SET_MSG(state, payload) {
          state.msg = payload
        },
        SET_CATEGORY(state, payload) {
          state.categories = payload
        }
      },
      actions: {
        // 动作，存储异步方法的地方
        async findAllCategories(context) {
          let res = await axios.get('http://47.94.46.113:8888/index/category/findAll')
          context.commit('SET_CATEGORY', res.data.data)
        }
      }
    })
    // 解构辅助函数
    let { mapState, mapActions } = Vuex

    let vm = new Vue({
      el: '#app',
      data: {
        data1: 'vue data'
      },
      computed: {
        // vuex中state里的数据，可以在vue实例的计算属性中直接获取
        ...mapState(['categories'])
      },
      methods: {
        ...mapActions(['findAllCategories'])
      },
      created() {
        // $store是注入进实例的状态机
        // dispatch是状态机中专门用来分发动作的一个函数
        // this.$store.dispatch('findAllUser')
        this.findAllCategories()
      },
      store
    })
  </script>
</body>

</html>